package com.sky.aop;
import com.sky.anno.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Component
@Aspect
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.AutoFill)")
    public void pc(){

    }


    @Around("pc() && @annotation(autoFill)")
    public Object autoFill(ProceedingJoinPoint pjp, AutoFill autoFill) throws Throwable {
        //1.获取方法参数并获取对象
        Object[] args = pjp.getArgs();
        //实体改变参数也会改变因为对应的是一个实体参数对象
        Object pojo = args[0];
        //2.通过pojo反射拿属性
        Class empolyee = pojo.getClass();
        //通过注解指定位置拿取操作类型
        OperationType operationType = autoFill.value();

        //通过emp实体对象拿取指定属性
        if(operationType==OperationType.INSERT){
            Field creatTime = empolyee.getDeclaredField("createTime");
            creatTime.setAccessible(true);
            creatTime.set(pojo, LocalDateTime.now());
            //设置创建人
            Field createUser = empolyee.getDeclaredField("createUser");
            createUser.setAccessible(true);
            createUser.set(pojo, BaseContext.getCurrentId());
        }
        //设置修改时间
        Field updateTime = empolyee.getDeclaredField("updateTime");
        updateTime.setAccessible(true);
        updateTime.set(pojo,LocalDateTime.now());
        //设置修改人
        Field updateUser = empolyee.getDeclaredField("updateUser");
        updateUser.setAccessible(true);
        updateUser.set(pojo,BaseContext.getCurrentId());
        Object result = pjp.proceed(args);
        return result;
    }
}
